﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Abp.Application.Services.Dto;
using Abp.AspNetCore.Mvc.Authorization;
using FwProject.Authorization;
using FwProject.Controllers;
using FwProject.Users;
using FwProject.Web.Models.Users;
using Abp.AspNetCore.Mvc.Extensions;
using FwProject.Authorization.Users;
using Microsoft.AspNetCore.Hosting;
using FwProject.Roles;
using FwProject.Users.Dto;
using FwProject.FactoryInfo;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Rendering;
using FwProject.Comm.ExcelUtil;
using System.Collections.Generic;
using Abp.Domain.Repositories;
using System.IO;
using System;
using Abp.Web.Models;
using FwProject.Authorization.Accounts;
using Abp.UI;
using FwProject.Authorization.Accounts.Dto;
using Hangfire.Annotations;
using Abp;

namespace FwProject.Web.Controllers
{
    [AbpMvcAuthorize(PermissionNames.Pages_Users)]
    public class UsersController : FwProjectControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly IRoleAppService _roleAppService;
        private readonly IAccountAppService _accountAppService;
        private readonly UserManager _userManager;
        private readonly IHostingEnvironment _env;
        private readonly IFactoryNameInfoAppService _factoryNameInfoAppService;
        public UsersController(IUserAppService userAppService, UserManager userManager, IHostingEnvironment env, IRoleAppService roleAppService, IFactoryNameInfoAppService factoryNameInfoAppService, IAccountAppService accountAppService)
        {
            _accountAppService = accountAppService;
            _userAppService = userAppService;
            _userManager = userManager;
            _env = env;
            _roleAppService = roleAppService;
            _factoryNameInfoAppService = factoryNameInfoAppService;
        }

        public async Task<ActionResult> Index(int size, int id = 1, string factoryid = "", string type = "", string keyword = "")
        {
            //var users = (await _userAppService.GetAll(new PagedResultRequestDto {MaxResultCount = int.MaxValue})).Items; // Paging not implemented yet
            //var roles = (await _userAppService.GetRoles()).Items;
            //var model = new UserListViewModel
            //{
            //    Users = users,
            //    Roles = roles
            //};
            if (size == 0)
                size = 20;
            var pagelist = await _userAppService.GetPagedListAsync(id, size, factoryid, type, keyword);
            if (Request.IsAjaxRequest())
            {
                return PartialView("IndexPartial", pagelist);
            }
            return View(pagelist);
        }



        public async Task<ActionResult> EditUserModal(long userId)
        {
            var user = await _userAppService.Get(new EntityDto<long>(userId));
            var roles = (await _userAppService.GetRoles()).Items;
            var model = new EditUserModalViewModel
            {
                User = user,
                Roles = roles
            };
            return View("_EditUserModal", model);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Create()
        {
            //var factoryinfos = await _factoryNameInfoAppService.GetAllAsync("");
            //ViewBag.Factoryinfos= factoryinfos.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.FactoryName });
            var roles = await _roleAppService.GetAllAsync("");
            ViewBag.RoleNames = roles.Select(c => new SelectListItem() { Value = c.Name, Text = c.DisplayName });
            return View();
        }

        [HttpPost]
        public async Task<JsonResult> CreateUser(CreateUserDto input)
        {
            await _userAppService.CreateAndGitIdAsync(input);

            return Json("");
        }

        public async Task<ActionResult> Edit(long id)
        {
            var entity = await _userAppService.GetEnterEntityAsync(id);
            //var factoryinfos = await _factoryNameInfoAppService.GetAllAsync("");
            //ViewBag.Factoryinfos = factoryinfos.Select(c => new SelectListItem() { Value = c.Id.ToString(), Text = c.FactoryName });
            var user = await _userManager.GetUserByIdAsync(id);
            IList<string> hasRoles = await _userManager.GetRolesAsync(user);

            var roles = await _roleAppService.GetAllAsync("");
            ViewBag.RoleNames = roles.Select(c => new SelectListItem() { Value = c.Name, Text = c.DisplayName, Selected = hasRoles.Contains(c.Name) });

            return View(entity);
        }

        [HttpPost]
        public async Task<JsonResult> EditUser(long id, UserEnterDto input)
        {
            await _userAppService.EditAsync(id, input);
            return Json(id);
        }


        public async Task<JsonResult> DeleteUser(long id)
        {
            await _userAppService.DeleteAsync(id);
            return Json(id);
        }

        /// <summary>
        /// 上传头像图片
        /// </summary>
        /// <param name="img"></param>
        [HttpPost]
        public JsonResult UploadImage()
        {
            return Json(base.UploadFile(_env, Request.Form.Files, FwProject.Authorization.Users.User.TempFileUrlPrefix));
        }

        public async Task<JsonResult> GetSuggestData(EmployeeType type, Guid? factoryinfoId, string keyword = "")
        {
            var list = await _userAppService.GetAllByTypeAsync(type, factoryinfoId, keyword);
            return Json(list);
        }

        public async Task<JsonResult> GetSuggestData2(string keyword = "")
        {
            var list = await _userAppService.GetAllListAsync(keyword);
            return Json(list);
        }

        public async Task<IActionResult> ExportExcel()
        {
            var list = await _userAppService.GetUserListAsync();
            return DoExcel<UserExportDto>(list, _env);

        }

        //重置密码
        [HttpPost]
        //[AbpMvcAuthorize(PermissionNames.HR_Employee_PasswordReset)]
        public async Task<JsonResult> PasswordReset(long id)
        {
            var user = await _userManager.GetUserByIdAsync(id);
            var result = await _userManager.ChangePasswordAsync(user, FwProject.Authorization.Users.User.DefaultPassword);
            if (result.Succeeded)
                return Json(new AjaxResponse("该账户密码已重置为系统默认密码：" + Authorization.Users.User.DefaultPassword));

            CheckErrors(result);//抛出错误
            return Json(new AjaxResponse("重置失败"));

        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public IActionResult EditPassword()
        {
            return View();
        }

        public JsonResult EditPwd(long id, ResetPasswordDto input)
        {
            if (input.RepeatPassword != input.NewPassword)
                throw new UserFriendlyException("两次输入的密码不一致！");

            _accountAppService.EditPassword(id, input.RepeatPassword);
            return Json(id);
        }

        public async Task<IActionResult> UserPushMessage(int id = 1, string factoryid = "", string type = "", string keyword = "")
        {
            var pagelist = await _userAppService.GetPagedListAsync(id, 15, factoryid, type, keyword);
            if (Request.IsAjaxRequest())
            {
                return PartialView("UserPushMessagePartial", pagelist);
            }
            return View(pagelist);
        }

        public IActionResult PushMessage(string ids)
        {
            ViewBag.ids = ids.Split(',');
            return View();
        }

        [HttpPost]
        public IActionResult PushMessage([NotNull]List<long> ids, string Message)
        {
            Check.NotNullOrEmpty(ids, nameof(List<long>));
            _userAppService.UserPushMessage(ids, Message);
            return Json(1);
        }
    }
}
